from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
import random

# settings.configure() before accessing settings
import trancer.settings

from utils.code.code import check_code
from trancer import settings


def send_sms_single(phone_num, template_code, code):
    """
    单条发送短信
    :param code: 5位数字验证码
    :param phone_num: 手机号
    :param template_code: 阿里云短信模板CODE 'register'->注册| 'login'->登陆 | 'reset'->重置
    :return:
    """
    # AccessKey ID
    key_id = settings.ALI_SMS_KEY_ID
    # AccessKey Secret
    key_secret = settings.ALI_SMS_KEY_SECRET
    # 签名名称
    sms_sign = settings.ALI_SMS_SIGN

    config = open_api_models.Config(
        # 必填，您的 AccessKey ID,
        access_key_id=key_id,
        # 必填，您的 AccessKey Secret,
        access_key_secret=key_secret
    )
    # 访问的域名
    config.endpoint = f'dysmsapi.aliyuncs.com'

    client = Dysmsapi20170525Client(config)

    send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
        sign_name=sms_sign,
        template_code=template_code,
        phone_numbers=phone_num,
        template_param='{"code":"' + f'{code}' + '"}'
    )
    runtime = util_models.RuntimeOptions()
    try:
        # 复制代码运行请自行打印 API 的返回值
        res = client.send_sms_with_options(send_sms_request, runtime)
        # res.to_map() 将res转换为dict类型
        return res.to_map()
    except Exception as error:
        # 如有需要，请打印 error
        # print(UtilClient.assert_as_string(error.message))
        # print('error')
        return None
